package com.gwtintegration.smartrf.util;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;

import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.sun.codemodel.CodeWriter;
import com.sun.codemodel.JPackage;

public class DeferredBindingCodeWriter extends CodeWriter {

	private final GeneratorContext context;
	private final TreeLogger logger;
	private PrintWriter printWriter;

	public DeferredBindingCodeWriter(TreeLogger logger, GeneratorContext context) {
		this.logger = logger;
		this.context = context;
	}

	@Override
	public OutputStream openBinary(JPackage pkg, String fileName) throws IOException {
		throw new UnsupportedOperationException();
	}

	@Override
	public Writer openSource(JPackage pkg, String fileName) throws IOException {

		if (fileName.endsWith(".java")) {
			fileName = fileName.substring(0, fileName.indexOf(".java"));
		}

		printWriter = context.tryCreate(logger, pkg.name(), fileName);

		// If tryCreate returns null is because the file is already created
		// this is a workaround to keep the CodeModel happy.
		if (printWriter == null) {
			return new NullWriter();
		}

		return printWriter;
	}

	@Override
	public void close() throws IOException {
		if (printWriter != null) {
			printWriter.close();
			context.commit(logger, printWriter);

			printWriter = null;
		}
	}
}
